package com.meida.module.arc.provider.util;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;

public class MyHeaderFooter extends PdfPageEventHelper {

    public PdfTemplate totalPage;
    Font hfFont;

    {
        try {
            hfFont = new Font(BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED), 8, Font.NORMAL);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    String str = "";

    public MyHeaderFooter(String str) {
        this.str = str;
    }

    /**
     * 打开文档时，创建一个总页数的模版
     * https://www.cnblogs.com/dalianpai/p/13530480.html
     */
    /*@Override
    public void onOpenDocument(PdfWriter writer, Document document) {
        PdfContentByte cb =writer.getDirectContent();
        totalPage = cb.createTemplate(30, 16);
    }*/
    @Override
    public void onEndPage(PdfWriter writer, Document document) {
        if (null == totalPage) {
            totalPage = writer.getDirectContent().createTemplate(30, 16);
        }
        try {
            PdfPTable table = new PdfPTable(1);
            table.setTotalWidth(PageSize.A4.getWidth() - 60);
            table.getDefaultCell().disableBorderSide(-1);
            table.getDefaultCell().setFixedHeight(40);
            //table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);

            //导出人
            table.addCell(new Phrase(str, hfFont));
            //再把表格写到页脚处  使用绝对定位
            table.writeSelectedRows(0, -1, 30, 20, writer.getDirectContent());
        } catch (Exception de) {
            throw new ExceptionConverter(de);
        }
    }

    /**
     * 全部完成后，将总页数的pdf模版写到指定位置
     */
   /* @SneakyThrows
    @Override
    public void onCloseDocument(PdfWriter writer, Document document) {
        String text = "总" + (writer.getPageNumber()) + "页";
        System.out.println(text);
        //ColumnText.showTextAligned(totalPage, Element.ALIGN_LEFT, new Paragraph(text,hfFont), 2, 2, 0);
        //创建字体
         //将最后的页码写入到总页码模板
        String totalNum = writer.getPageNumber() + "页";
        totalPage.beginText();
        totalPage.setFontAndSize(BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED), 5f);
        totalPage.showText(totalNum);
        totalPage.setHeight(16f);
        totalPage.endText();
        totalPage.closePath();
    }*/

}
